import http from '@ohos.net.http';

const TAG = "HttpClient"

export class HttpClient {

  private httpClient: http.HttpRequest;
  private requestMethodMap = {
    "GET": http.RequestMethod.GET,
    "POST": http.RequestMethod.POST,
    "PUT": http.RequestMethod.PUT,
    "DELETE": http.RequestMethod.DELETE
  }

  constructor() {
    this.createHttpRequest();
    this.onHeaderReceive();
  }

  private createHttpRequest() {
    console.info(TAG, "start create HttpRequest");
    this.httpClient = http.createHttp();
    console.info(TAG, "create HttpRequest sucess ");
  }


  public destroy() {
    this.httpClient.destroy();
    console.info(TAG, "HttpRequest destroyed")
  }

  private onHeaderReceive() {
    this.httpClient.on("headersReceive", (data) => {
      console.info(TAG, "ResponseHeader:" + JSON.stringify(data));
    })
  }


  /**
   * 根据url和请求参数，向服务端发送http请求
   * @param url
   * @param param
   */
  public async requestHttp(url: string, param: RequestParam) {

    console.info(TAG, "start request:" + JSON.stringify(param));

    let requestOption = {
      method: this.requestMethodMap[param.method],
      extraData: param.extraData,
      header: param.header,
      readTimeout: param.readTimeout,
      connectTimeout: param.connectTimeout
    }

    console.info(TAG, "the request param is:" + JSON.stringify(requestOption));
    let httpResponse = undefined;
    try {
      httpResponse = await this.httpClient.request(url, requestOption);
      console.info(TAG, "send request sucess,the response is:" + JSON.stringify(httpResponse));
      let videoList = JSON.parse(httpResponse.result as string).videoList;
      console.info(TAG, "the videoList form server:" + JSON.stringify(videoList));
      return videoList;
    } catch (e) {
      console.info(TAG + "send request fail :" + JSON.stringify(e));
      return undefined;
    } finally {
      this.destroy();
    }
//    console.info(TAG, "the request param is:" + JSON.stringify(requestOption));
//    let httpResponse=await this.httpClient.request(url, requestOption);
//    console.info(TAG, "send request sucess,the response is:" + JSON.stringify(httpResponse));
//    // @ts-ignore
//    let videoList=JSON.parse(httpResponse.result).videoList;
//    console.info(TAG,"the videoList form server:"+JSON.stringify(videoList));
//    return videoList;
  }
}

/**
 * 请求参数接口
 */
export interface RequestParam {

  method: string;
  extraData?: string | Object | ArrayBuffer;
  header?: Object; // default is 'content-type': 'application/json'

  readTimeout?: number; // default is 60s

  connectTimeout?: number; // default is 60s.
}

let httpClient: HttpClient = new HttpClient();

export {httpClient}